package com.hisense.hiioc.hismartplate.service;

import com.alibaba.fastjson.JSONObject;
import com.hisense.hiioc.hismartplate.entity.server.AppVersionEntity;
import com.hisense.hiioc.hismartplate.server.CoreManager;
import com.hisense.hiioc.hismartplate.server.DevClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.util.List;

/**
 * @Author: almo
 * @Date: 2018/12/27 下午4:41
 * @Version 1.0
 */
@Service
public class CoreManagerService implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {


    public static final String SYSTEM_REBOOT = "SYSTEM_REBOOT";
    public static final String RESOURCE_UPDATE = "RESOURCE_UPDATE";
    public static final String RESOURCE_ZIP_UPDATE = "RESOURCE_ZIP_UPDATE";
    public static final String RESOURCE_DELETE = "RESOURCE_DELETE";
    public static final String SOFTWARE_UPDATE = "SOFTWARE_UPDATE";
    public static final String SOFTWARE_INSTALL = "SOFTWARE_INSTALL";
    public static final String SOFTWARE_UNINSTALL = "SOFTWARE_UNINSTALL";
    public static final String SOFTWARE_VERSION_CHECK = "SOFTWARE_VERSION_CHECK";

    private CoreManager coreManager = CoreManager.getInstance();
    private int serverPort;

    @Autowired
    private TaskExecutor taskExecutor;

    public void updateApkByScreenId(String screenId, AppVersionEntity entity) {
        try {
           // StringBuilder stringBuilder = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress());
            StringBuilder stringBuilder = new StringBuilder("http://27.223.99.143");
            stringBuilder.append(":").append(serverPort).append("/apkFile/").append(entity.getUrl());
            entity.setUrl(stringBuilder.toString());
            System.out.println((screenId + " | " + SOFTWARE_UPDATE + " | " + entity.getUrl()));
            taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenId, SOFTWARE_UPDATE, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateApkForAll(AppVersionEntity entity) {
        try {
            //StringBuilder stringBuilder = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress());
             StringBuilder stringBuilder = new StringBuilder("http://27.223.99.143");
            stringBuilder.append(":").append(serverPort).append("/apkFile/").append(entity.getUrl());
            entity.setUrl(stringBuilder.toString());

            taskExecutor.execute(() -> coreManager.broadcastMsg(SOFTWARE_UPDATE, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void installApkByScreenId(String screenId, AppVersionEntity entity) {
        try {
            //StringBuilder stringBuilder = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress());
            StringBuilder stringBuilder = new StringBuilder("http://27.223.99.143");
            stringBuilder.append(":").append(serverPort).append("/apkFile/").append(entity.getUrl());
            entity.setUrl(stringBuilder.toString());
            System.out.println((screenId + " | " + SOFTWARE_INSTALL + " | " + entity.getUrl()));
            taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenId, SOFTWARE_INSTALL, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void installApkForAll(AppVersionEntity entity) {
        try {
            //StringBuilder stringBuilder = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress());
            StringBuilder stringBuilder = new StringBuilder("http://27.223.99.143");
            stringBuilder.append(":").append(serverPort).append("/apkFile/").append(entity.getUrl());
            entity.setUrl(stringBuilder.toString());

            taskExecutor.execute(() -> coreManager.broadcastMsg(SOFTWARE_INSTALL, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unInstallApkByScreenId(String screenId, AppVersionEntity entity) {
        try {
            System.out.println((screenId + " | " + SOFTWARE_UNINSTALL + " | " + entity.getUrl()));
            taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenId, SOFTWARE_UNINSTALL, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unInstallApkForAll(AppVersionEntity entity) {
        try {
            taskExecutor.execute(() -> coreManager.broadcastMsg(SOFTWARE_UNINSTALL, entity));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void updateResourceByScreenId(String screenId, String fileName, String path, String packageName, boolean isFile, boolean reboot) {
        try {
            //StringBuilder resFileUrl = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress()).append(":").append(serverPort);
            StringBuilder resFileUrl = new StringBuilder("http://27.223.99.143").append(":").append(serverPort);
            resFileUrl.append("/resFile/").append(fileName);
            JSONObject resUpdataMsg = new JSONObject();
            resUpdataMsg.put("remoteResPath", resFileUrl);
            resUpdataMsg.put("localResPath", path);
            resUpdataMsg.put("packageName", packageName);
            resUpdataMsg.put("fileName", fileName);
            resUpdataMsg.put("reboot", reboot);
            System.out.println(screenId + " | " + RESOURCE_UPDATE + " | " + resUpdataMsg);
            if (isFile)
                taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenId, RESOURCE_UPDATE, resUpdataMsg));
            else
                taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenId, RESOURCE_ZIP_UPDATE, resUpdataMsg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateResourceForAll(String screenId, String fileName, String path, String packageName, boolean isFile, boolean reboot) {
        try {
           // StringBuilder resFileUrl = new StringBuilder("http://" + InetAddress.getLocalHost().getHostAddress()).append(":").append(serverPort);
            StringBuilder resFileUrl = new StringBuilder("http://27.223.99.143").append(":").append(serverPort);
            resFileUrl.append("/resFile/").append(fileName);
            JSONObject resUpdataMsg = new JSONObject();
            resUpdataMsg.put("remoteResPath", resFileUrl);
            resUpdataMsg.put("localResPath", path);
            resUpdataMsg.put("packageName", packageName);
            resUpdataMsg.put("fileName", fileName);
            resUpdataMsg.put("reboot", reboot);
            System.out.println(screenId + " | " + RESOURCE_ZIP_UPDATE + " | " + resUpdataMsg);
            if (isFile)
                taskExecutor.execute(() -> coreManager.broadcastMsg(RESOURCE_ZIP_UPDATE, resUpdataMsg));
            else
                taskExecutor.execute(() -> coreManager.broadcastMsg(RESOURCE_ZIP_UPDATE, resUpdataMsg));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void softwareVersionCheckByScreenId(String screenID, List<String> packages) {
        try {
            JSONObject resUpdataMsg = new JSONObject();
            resUpdataMsg.put("packageNames", packages);
            System.out.println(screenID + " | " + RESOURCE_UPDATE + " | " + resUpdataMsg);
            taskExecutor.execute(() -> coreManager.sendMsgByScreenId(screenID, SOFTWARE_VERSION_CHECK, resUpdataMsg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void softwareVersionCheckForAll(List<String> packages) {
        try {
            JSONObject resUpdataMsg = new JSONObject();
            resUpdataMsg.put("packageNames", packages);
            taskExecutor.execute(() -> coreManager.broadcastMsg(SOFTWARE_VERSION_CHECK, resUpdataMsg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean getDeviceConnectStateByScreenId(String screenID) {

        DevClient devClient = coreManager.getDevClientByScreenId(screenID);

        if (devClient == null || !devClient.isAuthorized())
            return false;

        return devClient.getChannel() != null && devClient.getChannel().isActive() && devClient.getChannel().isOpen();
    }

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
        serverPort = event.getEmbeddedServletContainer().getPort();
    }
}
